//build:20240524
//This simplifies the use of the micro-light communication protocol in MQTT components by encapsulating MQTT within this worker. Users only need to subscribe to events in the event center to listen to MQTT.
import log from './dxLogger.js'
import net from './dxNet.js'
import mqtt from './dxMqtt.js'
import dxMap from './dxMap.js'
import std from './dxStd.js'
import * as os from "os";
const map = dxMap.get('default')
const id = "{{id}}"
const options = map.get("__mqtt__run_init" + id)
let connected = false
function run() {
    mqtt.init(options.mqttAddr, options.clientId, options.username, options.password, options.prefix, options.qos, options.willTopic, options.willMessage, options.id)
    log.info('mqtt start......,id =', id)
    os.sleep(2000)//Wait 2 seconds
    std.setInterval(() => {
        try {
            if (mqtt.isConnected(options.id) && net.getStatus().connected) {
                if (!connected) {
                    _fireChange(true)
                    if (options.subs) {
                        mqtt.subscribes(options.subs, options.qos, options.id)
                    }
                }
            } else {
                if (connected) {
                    _fireChange(false)
                }
                // Reconnect
                mqtt.reconnect(options.willTopic, options.willMessage, options.id)
                os.sleep(2000)//Wait 2 seconds after reconnecting
            }
        } catch (error) {
            log.error(error)
        }
    }, 3000)
    std.setInterval(() => {
        // After successful connection, enter message listening mode.
        if (connected) {
            if (!mqtt.msgIsEmpty(options.id)) {
                let msg = mqtt.receive(options.id)
                __bus.fire(mqtt.RECEIVE_MSG + options.id, msg)//When you call `bus.newworker`, you will import `eventbus` as `__bus`.
            }
        }
    }, 10);
}

try {
    run()
} catch (error) {
    log.error(error)
}

function _fireChange(status) {
    __bus.fire(mqtt.CONNECTED_CHANGED + options.id, status ? 'connected' : 'disconnected')//When you call `bus.newworker`, you will import `eventbus` as `__bus`.
    connected = status
}
